<?php namespace App\Models\Power;

use App\Models\Base\PowerBase;
use App\Models\Power\Pile;
use App\Models\Power\Gun;
use App\Models\Power\Price;

class Stop extends PowerBase {

    protected $connction='jmft_power';
    protected $table = 'cdz_electric_stop';

    protected $fillable = [];

    protected $dates = [];

    public static $rules = [
        // Validation rules
    ];

     /**
     * 首页获取电站数据
     * params Array condition
     */
    public static function getStop($params = []) {

        //根据经纬度查询最大最小经纬度范围
        $range = getPositionRange($params['lng'], $params['lat']);
        $query = self::query();
		$query -> whereBetween('lng', [$range['minLng'],$range['maxLng']]);
        $query -> whereBetween('lat', [$range['minLat'],$range['maxLat']]);
        $data = $query-> get() -> toArray();

        if(isset($params['condition'])) {
            $condition = json_decode($params['condition'],true);
        }   

        if(isset($condition)) {

            foreach($condition as $key => $value) {

                if (isset($condition[$key]['type'])) {
                    $type = $condition[$key]['type'];
                }

                if (isset($condition[$key]['standard'])) {
                    $standard = $condition[$key]['standard'];
                }
        
                if (isset($condition[$key]['p_money'])) {
                    $pmoney = $condition[$key]['p_money'];
                }

                if (isset($condition[$key]['using'])) {
                    $using = $condition[$key]['using'];
                }

            }

        }

        // dd(strstr($type,'1'));
        foreach($data as $key => $value) {

            $data[$key]['count_pile'] = self::getCountPile($value['id']);
            $data[$key]['pile_info'] = self::getPileInfo($value['id']);
            $pile_info = self::getPileInfo($value['id']);

            if(isset($type)&&strstr($type,'1')) {
                if($pile_info['quick']['count']>=1&&$pile_info['slow']['count']<1&&!strstr($type,'2')) {
                    unset($data[$key]);
                }
            }

            if(isset($type)&&strstr($type,'2')) {
                if($pile_info['slow']['count']>=1&&$pile_info['quick']['count']<1&&!strstr($type,'1')) {
                    unset($data[$key]);
                }
            }

            if(isset($using)&&$using==1) {
                if($pile_info['slow']['not_using']<1&&$pile_info['quick']['not_using']<1) {
                    unset($data[$key]);
                }
            }

            if(isset($standard)&&strstr($standard,'1')) {
                if($pile_info['has_el']!=1&&!strstr($standard,'2')) {
                    unset($data[$key]);
                }
            }

            if(isset($standard)&&strstr($standard,'2')) {
                if($pile_info['has_fif']!=1&&!strstr($standard,'1')) {
                    unset($data[$key]);
                }
            }

            if(isset($pmoney)&&strstr($pmoney,'2')) {
                if($pile_info['p_money']!=2&&!strstr($pmoney,'1')) {
                    unset($data[$key]);
                }
            }

            if(isset($pmoney)&&strstr($pmoney,'1')) {
                if($pile_info['p_money']==2&&!strstr($pmoney,'2')) {
                    unset($data[$key]);
                }
            }

        }

        return $data;

    }

    /**
     * 首页获取电站数据
     * params Array condition
     */
    public static function getStopByNo($condition = []) {

        $gun = new Gun();
        $price = new Price();
        $query = self::query();
		$query -> whereNo($condition['no']);
        $data = $query-> first();
        $data['pile_info'] = self::getPileInfo($data['id']);
        $data['pile_list'] = self::getPileList($data['id']);

        return $data;

    }

    /**
     * 根据电站id查询电站电桩列表数据
     * param1 int $stop_id
     */
    public static function getPileList($stop_id) {

        $result = [];
        $pile = Pile::where('stop_id', $stop_id) -> where('status', 1)-> get() -> toArray(); 
        // dd($pile);
        if($pile) {

            $gun = new Gun();
            foreach($pile as $key => $value) {
                $check_gun = $gun -> getPileUsing($value['no'], $value['id']);
                $pile[$key]['using'] = 0;
                $pile[$key]['using'] =  $check_gun['is_using'];
                $pile[$key]['count_gun'] = 0;
                $pile[$key]['count_not_using'] = 0;
                $pile[$key]['count_gun'] = $check_gun['count_gun'];
                $pile[$key]['count_not_using'] = $check_gun['count_not_using'];
            }

            $result = $pile;

        }

        return $result;

    }

    /**
     * 根据关键字获取电桩
     * params String params
     */
    public static function findByKeyword($params = '') {

        $result = ['data' => [], 'range' => []];
        $query = self::query();
        $query -> whereLike($params);
        $data = $query->get()->toArray();

        if($data) {
            foreach($data as $key => $value) {
                $pile_info = self::getPileInfo($value['id']);
                $data[$key]['pile_info'] = $pile_info;
            }
            $result = ['data' => $data, 'range' => array_column($data, 'id')];
        }

        return $result;
    }

    /**
     * 根据电站id查询电站电桩数量
     * param1 int $stop_id
     */
    public static function getCountPile($stop_id = 0) {

        $pile = Pile::where('stop_id', $stop_id) -> get() -> toArray();
        
        if($pile) {
            return count($pile);
        }

        return 0;

    }

    
    /**
     * 根据电站id获取电桩信息
     * param1 int $stop_id
     */
    public static function getPileInfo($stop_id) {

        $price = new Price();
        $result = ['quick' => ['count' => 0, 'not_using' => 0], 'slow' => ['count' => 0, 'not_using' => 0], 'price' => ['electric' => '0', 'service' => '0'], 'p_money'=>2,'has_el'=>0, 'has_fif'=>0];
        $pile = Pile::where('stop_id', $stop_id) -> where('status', 1)-> get() -> toArray(); 
        $gun = new Gun();

        if(count($pile) == 1) {

            $result['p_money'] = $pile[0]['p_money'];
            if($pile[0]['standard'] == 1) {
                $result['has_el'] = 1;
            }
            if($pile[0]['standard'] == 2) {
                $result['has_fif'] = 1;
            }
            //获取电费范围
            $price_result = $price -> getPilePrice($pile[0]['no'], $pile[0]['id']);

            if($price_result['max_electric'] != $price_result['min_electric']) {
                $result['price']['electric'] = $price_result['min_electric'] . '-' . $price_result['max_electric'];
            } else {
                $result['price']['electric'] = $price_result['max_electric'];
            }

            //获取服务费范围
            $price_result = $price -> getPilePrice($pile[0]['no'], $pile[0]['id']);
            if($price_result['max_service'] != $price_result['min_service']) {
                $result['price']['service'] = $price_result['min_service'] . '-' . $price_result['max_service'];
            } else {
                $result['price']['service'] = $price_result['max_service'];
            }

            if($pile[0]['type'] == 1) {
                $result['quick']['count'] = 1;
                if($gun -> getPileUsing($pile[0]['no'], $pile[0]['id'])['is_using'] == 0) {
                    $result['quick']['not_using'] += 1;
                } 
            } else if($pile[0]['type'] == 2) {
                $result['slow']['count'] = 1;
                if($gun -> getPileUsing($pile[0]['no'], $pile[0]['id'])['is_using'] == 0) {
                    $result['slow']['not_using'] += 1;
                } 
            } 

        } else if(count($pile) > 1) {

            $result['p_money'] = $pile[0]['p_money'];

            //初始化最大最小值
            $max_electric = $price -> getPilePrice($pile[0]['no'], $pile[0]['id'])['max_electric'];
            $max_service = $price -> getPilePrice($pile[0]['no'], $pile[0]['id'])['max_service'];
            $min_electric = $price -> getPilePrice($pile[0]['no'], $pile[0]['id'])['min_electric'];
            $min_service = $price -> getPilePrice($pile[0]['no'], $pile[0]['id'])['min_service'];

            foreach($pile as $key => $value) {

                if($pile[$key]['standard'] == 1) {
                    $result['has_el'] = 1;
                }
                if($pile[$key]['standard'] == 2) {
                    $result['has_fif'] = 1;
                }

                if($value['p_money'] != $result['p_money']) {
                    $result['p_money'] = 3;
                }
                if($value['type'] == 1) {
                    $result['quick']['count'] += 1;
                    if($gun -> getPileUsing($value['no'], $value['id'])['is_using'] == 0) {
                        $result['quick']['not_using'] += 1;
                    } 
                } else if($value['type'] == 2) {
                    $result['slow']['count'] += 1;
                    if($gun -> getPileUsing($value['no'], $value['id'])['is_using'] == 0) {
                        $result['slow']['not_using'] += 1;
                    } 
                }

                if($key != 0) {

                    //获取当前电桩的电费服务费 与最大最小值作比较
                    $price_result = $price -> getPilePrice($pile[$key]['no'], $pile[$key]['id']);

                    if(round($price_result['max_electric'],2) > round($max_electric,2)) {
                        $max_electric = $price_result['max_electric'];
                    }
                    if(round($price_result['max_service'],2) > round($max_service,2)) {
                        $max_service = $price_result['max_service'];
                    }
    
                    if(round($price_result['min_electric'],2) < round($min_electric,2)) {
                        $min_electric = $price_result['min_electric'];
                    }
                    if(round($price_result['min_service'],2) < round($min_service,2)) {
                        $min_service = $price_result['min_service'];
                    }

                }

            }

            if($max_electric != $min_electric) {
                $result['price']['electric'] = $min_electric . '-' . $max_electric;
            } else {
                $result['price']['electric'] = $max_electric;
            }

            if($max_service != $min_service) {
                $result['price']['service'] = $min_service . '-' . $max_service;
            } else {
                $result['price']['service'] = $max_service;
            }

            $total = round($min_electric + $min_service, 2) . '-' . round($max_electric + $max_service, 2);
            $result['price']['detail'] = [['during' => '00:00-24:00', 'electric' => $result['price']['electric'], 'service' => $result['price']['service'], 'total'=>$total]];

        }

        return $result;

    }

    /**
     * 和Pile模型的一对多关联
     */
    public function pile() {
        return $this->hasMany('App\Models\Pile', 'stop_id');
    }

    public function scopeWhereLike($query, $keyword)
    {
        return $query->where('address', 'like', '%'.$keyword.'%') -> orWhere('name', 'like', '%'.$keyword.'%');
    }


}
